package com.project.finance.mobile.user.controller;

import com.project.finance.common.cosconfig.UploadImgConfig;
import com.project.finance.common.po.TbUsers;
import com.project.finance.common.resultconfig.Result;
import com.project.finance.common.resultconfig.ResultGenerator;
import com.project.finance.mobile.user.service.PersonalInfoService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: Brendan Li
 * @description 个人信息
 * @Date: 2019/12/09/20:20
 */
@RestController
public class PersonalInfoController {
    private static final Logger logger= LogManager.getLogger(PersonalInfoController.class);

    @Autowired
    private PersonalInfoService infoService;
    @Autowired
    private UploadImgConfig uploadImgConfig;

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "modifyUser",method = RequestMethod.PATCH)
    public Result updateUser(@RequestBody TbUsers user){
        int i = infoService.updateUser(user);
        if (i > 0){
            return ResultGenerator.apiSuccess("修改成功");
        }
        return ResultGenerator.apiError("修改失败");
    }

    /**
     * 更新用户头像
     * @param userId
     * @param userIcon
     * @return
     */
    @RequestMapping(value = "modifyIcon",method = RequestMethod.POST)
    public Result modifyUserImg(@RequestParam(value = "userId") Integer userId,
                                @RequestParam("userIcon") MultipartFile userIcon){
        String iconImg = "https://farmimg-1251492284.cos.ap-chengdu.myqcloud.com/"+userId+"icon";
        logger.info("userId : " + userId + " userIcon : " + userIcon);
        try {
            boolean uploadIcon = uploadImgConfig.uploadFile(userIcon, userId + "icon");
            if (uploadIcon){
                int i = infoService.updateUserImg(userId, iconImg);
                if (i > 0){
                    return ResultGenerator.apiError("上传成功");
                }
            }
            return ResultGenerator.apiError("上传失败");
        } catch (IOException e) {
            return ResultGenerator.apiError("上传失败");
        }
    }
}
